#include "returnbook.h"
#include "ui_returnbook.h"

#include <QCheckBox>
#include <QFile>
#include <QtAlgorithms>
#include <QDate>
#include <QDir>
#include <QMessageBox>
#include <QTextCodec>

ReturnBook::ReturnBook(QWidget *parent)
    : QWidget{parent},ui(new Ui::ReturnBook)
{
    ui->setupUi(this);
    initWindow();
    addEvents();
}

ReturnBook::~ReturnBook(){
    delete ui;
}
//初始化窗口
void ReturnBook::initWindow(){
    this->setLayout(ui->mainLayout);
    // 禁止所有单元格编辑
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    // 隐藏垂直表头
    ui->tableWidget->verticalHeader()->setVisible(false);
    // 禁止调整列宽
    QHeaderView *header = ui->tableWidget->horizontalHeader();
    header->setSectionResizeMode(QHeaderView::Fixed);  // 设置列宽为固定

    QString separator = QDir::separator();
    QString currentDir= getCurrentCppDirectory();
    qDebug()<<"当前目录："<<currentDir;
    borroweredBookFilePath="borrowbooks.txt";
    returnedBookFilePath="HistoryBooks.txt";

    borroweredBookfile=new QFile(borroweredBookFilePath);
    borroweredBookStream=new QTextStream(borroweredBookfile);
    QTextCodec* codec = QTextCodec::codecForName("UTF-8");
    borroweredBookStream->setCodec(codec);

    returnedBookfile=new QFile(returnedBookFilePath);
    returnedBookStream=new QTextStream(returnedBookfile);
    returnedBookStream->setCodec(codec);

    initBooks();

    currentShowData=borroweredBooks;
    isAscendingOrder=true;

    setDataToTable(isAscendingOrder);

    isAllSelected=false;

    //ctrlAShortCut=new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_A), this);
    //ui->allSelectButton->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_A));
}
//添加事件
void ReturnBook::addEvents(){
    QObject::connect(ui->orderMethodComboBox,&QComboBox::currentTextChanged,this,[this](){
        qDebug()<<"切换顺序";
        isAscendingOrder=!isAscendingOrder;
        setDataToTable(isAscendingOrder);
    });

    QObject::connect(ui->allSelectButton,&QPushButton::clicked,this,&ReturnBook::allSelectButtonEvent);

    QObject::connect(ui->restoreButton,&QPushButton::clicked,this,&ReturnBook::restoreButtonEvent);

    QObject::connect(ui->searchButton,&QPushButton::clicked,this,&ReturnBook::searchEvent);

    QObject::connect(ui->clearButton,&QPushButton::clicked,this,[this](){
        qDebug()<<"清空按钮点击";
        ui->lineEdit->clear();
        ui->lineEdit->setFocus();
    });

}
//初始图书信息
void ReturnBook::initBooks(){
    borroweredBooks.clear();
    //QFile file(borroweredBookFilePath);
    if (borroweredBookfile->open(QIODevice::ReadOnly | QIODevice::Text))
    {
        //QTextStream in(&file);
        while (!borroweredBookStream->atEnd())
        {
            QString line = borroweredBookStream->readLine();

            qDebug()<<"数据："<<line;
            QStringList dataList = line.split("/");

            QString name=dataList[0];
            QString publisher=dataList[1];
            QString author=dataList[2];
            QString ISBN=dataList[3];
            QString categroy=dataList[4];
            QString collectionLocation=dataList[5];
            int currentCollection=dataList[6].toInt();
            int allCollection=dataList[7].toInt();
            QDate loanTime=QDate::fromString(dataList[8],"yyyy-MM-dd");

            //qDebug()<<name<<"/"<<publisher<<"/"<<allCollection<<" "<<loanTime.toString();
            QCheckBox*checkBox=new QCheckBox();

            BorrowedBook*book=new BorrowedBook(name,publisher,author,ISBN,categroy,collectionLocation,currentCollection,allCollection,loanTime,checkBox);
            connect(checkBox,&QCheckBox::toggled,this,[book](bool isChecked){
                qDebug()<<"勾选事件触发:"<<book->getName();
                book->setIsChecked(isChecked);
            });
            borroweredBooks.append(book);
        }
        borroweredBookfile->close();
    }
    else
    {
        qDebug() << "无法打开文件，错误信息：" << borroweredBookfile->errorString();
    }
    std::sort(borroweredBooks.begin(),borroweredBooks.end(),[](BorrowedBook *a, BorrowedBook *b) {
        return a->getLoanTime() < b->getLoanTime(); // 根据借阅时间排序
    });
}

//将图书信息设置在表格中
void ReturnBook::setDataToTable(bool isAscendingOrder) {

    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);

    // 对数据进行排序操作，将排序逻辑提取成一个单独的函数，增强可读性和可维护性
    QList<BorrowedBook*> sortedData = sortData(currentShowData, isAscendingOrder);

    // 填充表格
    for (int row = 0; row < sortedData.size(); row++) {
        ui->tableWidget->insertRow(ui->tableWidget->rowCount());
        ui->tableWidget->setRowHeight(row,50);

        //保持勾选状态
        QCheckBox* newCheckBox=new QCheckBox();
        BorrowedBook*book=sortedData[row];
        QObject::connect(newCheckBox,&QCheckBox::toggled,this,[book](bool isChecked){
            qDebug()<<"勾选事件触发:"<<book->getName();
            book->setIsChecked(isChecked);
        });
        newCheckBox->setChecked(sortedData[row]->getIsChecked());


        sortedData[row]->setCheckBox(newCheckBox);
        // 设置QCheckBox在第一列，优化了内存管理，确保对象生命周期合理
        setCellWidgetSafely(row, 0,newCheckBox);

        // 设置各列数据，封装成独立的函数，使代码结构更清晰
        setTableItem(row, 1, sortedData[row]->getISBN(), Qt::AlignCenter, 12);
        setTableItem(row, 2, sortedData[row]->getName(), Qt::AlignCenter, 12);
        setTableItem(row, 3, sortedData[row]->getAuthor(), Qt::AlignCenter, 12);
        setTableItem(row, 4, sortedData[row]->getPublisher(), Qt::AlignCenter, 12);
        setTableItem(row, 5, sortedData[row]->getCategory(), Qt::AlignCenter, 12);
        setTableItem(row, 6, sortedData[row]->getCollectionLocation(), Qt::AlignCenter, 12);
        setTableItem(row, 7, sortedData[row]->getLoanTime().toString("yyyy-MM-dd"), Qt::AlignCenter, 12);

    }

    ui->countLabel->setText("共"+QString::number(currentShowData.size())+"/"+QString::number(borroweredBooks.size())+"条数据");
    ui->countLabel->setAlignment(Qt::AlignRight);
}

// 辅助函数：对数据进行排序
QList<BorrowedBook*> ReturnBook::sortData(const QList<BorrowedBook*>& data, bool isAscendingOrder) {
    QList<BorrowedBook*>result = data;
    if (!isAscendingOrder) {
        std::reverse(result.begin(), result.end());
    }
    return result;
}

// 辅助函数：安全地设置CellWidget，处理可能的内存相关问题，比如指针有效性等
void ReturnBook::setCellWidgetSafely(int row, int column, const QWidget* widget) {
    // 删除已有控件（如果存在）
    QWidget* existingWidget = ui->tableWidget->cellWidget(row, column);
    if (existingWidget) {
        delete existingWidget;  // 删除旧控件
    }
    if (widget && ui->tableWidget) {
        ui->tableWidget->setCellWidget(row, column, const_cast<QWidget*>(widget));
    }
}

// 辅助函数：统一设置表格项的格式和内容
void ReturnBook::setTableItem(int row, int column, const QString& text, Qt::Alignment alignment, int fontSize) {
    QTableWidgetItem* item = new QTableWidgetItem(text);
    QFont font = item->font();
    font.setPointSize(fontSize);
    item->setFont(font);
    item->setTextAlignment(alignment);
    ui->tableWidget->setItem(row, column, item);

}

//根据搜索设置数据
void ReturnBook::setDataToTable(QString searchType,QString searchLine,bool isAscendingOrder){
    currentShowData.clear();
    if(searchLine==""){
        currentShowData=borroweredBooks;
        setDataToTable(isAscendingOrder);
        return;
    }

    if(searchType=="编号"){
        for(BorrowedBook*book:borroweredBooks){
            if(book->getISBN().contains(searchLine)){
                currentShowData.append(book);
            }
        }
    }else if(searchType=="书名"){
        for(BorrowedBook*book:borroweredBooks){
            if(book->getName().contains(searchLine)){
                currentShowData.append(book);
            }
        }
    }else if(searchType=="作者"){
        for(BorrowedBook*book:borroweredBooks){
            if(book->getAuthor().contains(searchLine)){
                currentShowData.append(book);
            }
        }
    }else if(searchType=="出版社"){
        for(BorrowedBook*book:borroweredBooks){
            if(book->getPublisher().contains(searchLine)){
                currentShowData.append(book);
            }
        }
    }else if(searchType=="类别"){
        for(BorrowedBook*book:borroweredBooks){
            if(book->getCategory().contains(searchLine)){
                currentShowData.append(book);
            }
        }
    }else if(searchType=="馆藏地点"){
        for(BorrowedBook*book:borroweredBooks){
            if(book->getCollectionLocation().contains(searchLine)){
                currentShowData.append(book);
            }
        }
    }else if(searchType=="借阅时间"){
        for(BorrowedBook*book:borroweredBooks){
            if(book->getLoanTime().toString("yyyy-MM-dd").contains(searchLine)){
                currentShowData.append(book);
            }
        }
    }

    setDataToTable(isAscendingOrder);
}

//将归还的书加入历史记录
void ReturnBook::addDataToHistory(QList<BorrowedBook*>books){
    // 打开文件（以写模式打开，如果文件不存在会创建）
    //QFile file(returnedBookFilePath);
    if (!returnedBookfile->open(QIODevice::Append | QIODevice::Text)) {
        qDebug() << "无法打开文件，错误信息：" << returnedBookfile->errorString();
        return;
    }
    for(BorrowedBook*book:books){
        // 创建一个 QTextStream 对象来写入文件
        //QTextStream out(&file);

        //写出文本
        *returnedBookStream<<book->getName()<<"/"<<book->getPublisher()<<"/"<<book->getAuthor()<<"/"<<book->getISBN()<<"/"
            <<book->getCategory()<<"/"<<book->getCollectionLocation()<<"/"
            <<book->getCurrentCollection()<<"/"<<book->getAllCollection()<<"/"<<book->getLoanTime().toString("yyyy-MM-dd")
                            <<"/"<<QDate::currentDate().toString("yyyy-MM-dd")<<'\n';
    }
    // 关闭文件
    returnedBookfile->close();

    QList<Book*>restoreBooks;
    for(BorrowedBook*book:books){
        Book*b=static_cast<Book*>(book);
        restoreBooks.append(b);
    }

    QFile bookFile("book.txt");
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    if (bookFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {

        QTextStream in(&bookFile);
        in.setCodec(codec);
        QStringList allLines;
        while (!in.atEnd())
        {
            QString line = in.readLine();
            QStringList parts = line.split("/");
            qDebug()<<"1111111111111111111:"<<restoreBooks.size();
            for (Book*book:restoreBooks) {
                if (parts[3] == book->getISBN())
                {
                    bool ok;
                    int currentCount = parts[6].toInt(&ok);
                    qDebug()<<currentCount;
                    if (ok)
                    {
                        parts[6] = QString::number(currentCount + 1);
                        line = parts.join("/");
                    }

                }


            }
            allLines.append(line);
            qWarning()<<line;

        }
        bookFile.close();

        //写文本进行更新
        if (bookFile.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QTextStream updateOut(&bookFile);
            updateOut.setCodec(codec);
            for (const QString &line : allLines)
            {
                updateOut << line << "\n";
            }
            bookFile.close();
        }



    }
}

//从借阅书记录中删除归还的
void ReturnBook::deleteDataFromBorrowed(QList<BorrowedBook*>books){
    //QFile file(borroweredBookFilePath);
    /*if (!file.exists()) {
        qDebug() << "文件不存在：" << borroweredBookFilePath;
    }*/
    if (!borroweredBookfile->open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件，错误信息：" << borroweredBookfile->errorString();
        return;
    }
    for(BorrowedBook*book:books){
        // 打开文件（以写模式打开，如果文件不存在会创建）
        // 创建一个 QTextStream 对象来写入文件
        //QTextStream out(&file);

        //写出文本
        *borroweredBookStream<<book->getName()<<"/"<<book->getPublisher()<<"/"<<book->getAuthor()<<"/"<<book->getISBN()<<"/"
                            <<book->getCategory()<<"/"<<book->getCollectionLocation()<<"/"
                           <<book->getCurrentCollection()<<"/"<<book->getAllCollection()<<"/"<<book->getLoanTime().toString("yyyy-MM-dd")<<'\n';
    }
    // 关闭文件
    borroweredBookfile->close();
}
//搜索按钮触发的事件
void ReturnBook::searchEvent(){
    qDebug()<<"搜索按钮按下";
    ui->lineEdit->setFocus();
    QString searchType=ui->searchComboBox->currentText();
    QString searchLine=ui->lineEdit->text();
    qDebug()<<"搜索类型："<<searchType<<",搜索关键字："<<searchLine;
    setDataToTable(searchType,searchLine,isAscendingOrder);
}

//归还按钮触发的事件
void ReturnBook::restoreButtonEvent(){
    returnBooks.clear();
    qDebug()<<"归还按钮点击";
    QString names="";
    for(BorrowedBook*book:currentShowData){
        qDebug()<<book->getName()<<":"<<book->getCheckBox()->isChecked();
        if(book->getCheckBox()->isChecked()){
            /*currentShowData.removeOne(book);
            borroweredBooks.removeOne(book);*/
            //addDataToHistory(book);
            returnBooks.append(book);
            names+=book->getName()+",";
        }
    }
    for(BorrowedBook*book:returnBooks){
        qDebug()<<book->getName();
        currentShowData.removeOne(book);
        borroweredBooks.removeOne(book);
    }
    deleteDataFromBorrowed(borroweredBooks);
    addDataToHistory(returnBooks);

    setDataToTable(isAscendingOrder);
    if(names==""){
        QMessageBox::information(this,"提示","请至少选择一本书归还");
    }else{
        QMessageBox::information(this,"成功",names.remove(names.size()-1,1)+"归还成功");
    }
}
//全选按钮触发的事件
void ReturnBook::allSelectButtonEvent(){
    qDebug()<<"全选按钮点击";
    if(!isAllSelected){
        for(BorrowedBook*book:currentShowData){
            book->getCheckBox()->setChecked(true);
            //qDebug()<<book->getCheckBox()->isChecked();
        }
        ui->allSelectButton->setText("取消全选");
        isAllSelected=true;
    }else{
        for(BorrowedBook*book:currentShowData){
            book->getCheckBox()->setChecked(false);
            //qDebug()<<book->getCheckBox()->isChecked();
        }
        ui->allSelectButton->setText("全选");
        isAllSelected=false;
    }
}

//重写大小调整事件
void ReturnBook::resizeEvent(QResizeEvent *event) {
    qDebug()<<"窗口大小调整:"<<event->size();
}

void ReturnBook::keyPressEvent(QKeyEvent *event){
    qDebug()<<"按钮监听："<<event->key()<<" "<<event->text();
    if(event->key()==Qt::Key_Return||event->key()==Qt::Key_Enter){
        QWidget*focusWidget=this->focusWidget();
        if(qobject_cast<QLineEdit*>(focusWidget)){
            searchEvent();
        }
    }
}
// 定义一个函数来获取当前cpp文件所在目录
QString ReturnBook::getCurrentCppDirectory()
{
    QString filePath = __FILE__;
    QDir dir(filePath);
    dir.cdUp();
    return dir.path();
}

QList<BorrowedBook *> ReturnBook::getReturnBooks() const
{
    return returnBooks;
}

void ReturnBook::setReturnBooks(const QList<BorrowedBook *> &newReturnBooks)
{
    returnBooks = newReturnBooks;
}

QList<BorrowedBook *> ReturnBook::getCurrentShowData() const
{
    return currentShowData;
}

void ReturnBook::setCurrentShowData(const QList<BorrowedBook *> &newCurrentShowData)
{
    currentShowData = newCurrentShowData;
}

QList<BorrowedBook *> ReturnBook::getBorroweredBooks() const
{
    return borroweredBooks;
}

void ReturnBook::setBorroweredBooks(const QList<BorrowedBook *> &newBorroweredBooks)
{
    borroweredBooks = newBorroweredBooks;
}




